package messageMeServer.utility;

import java.io.File;
import java.util.List;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import messageMeUtility.interfaces.IUser;

public class UserDataWriter {

	public UserDataWriter() {

	}

	public void write(List<IUser> users) {
		try {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.newDocument();
			Element usersElement = doc.createElement("Users");

			for (IUser user : users) {
				usersElement.appendChild(this.getUser(user, doc));
			}

			doc.appendChild(usersElement);
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File(
					".\\data\\Users2.xml"));
			transformer.transform(source, result);
		}

		catch (Exception e) {

		}
	}

	private Element getUser(IUser user, Document doc) {
		Element result = doc.createElement("User");

		result.setAttribute("name", user.getUsername());
		result.setAttribute("email", user.getEmail());
		result.setAttribute("password", user.getPassword());

		return result;
	}
}
